import { Button, Modal, Popconfirm } from "antd";
import { cloneDeep } from "lodash";
import { FC, useContext, useMemo, useState } from "react";
import { OperateGoodsContext } from "../../../OperateGoods";
import AttributeTable, { AttributeTableRecord } from "../../AttributeTable";

interface AddOptionModalProps {
	open: boolean;
	setOpen: (open: boolean) => void;
}
const AddOptionModal: FC<AddOptionModalProps> = ({ open, setOpen }) => {
	const { setSkuOptions, skuOptionRef } = useContext(OperateGoodsContext);
	const [options, setOptions] = useState<AttributeTableRecord[]>([]);
	const someSkuEmpty = useMemo(() => options?.some(item => !item.key || item.valueList.some(item1 => !item1.name)), [options]);
	return (
		<Modal
			open={open}
			forceRender
			width="calc(100vw - 400px)"
			closable={false}
			cancelButtonProps={{ hidden: true }}
			footer={
				someSkuEmpty ? (
					<Popconfirm
						title="当前有选项名/选项值为空，确认将自动删除为空的选项，是否确认？"
						onConfirm={() => {
							const copiedData = cloneDeep(skuOptionRef.current?.getData() || []);
							for (let index = 0; index < copiedData.length; index++) {
								const item = copiedData[index];
								if (!item.key || item.valueList.some(item1 => !item1.name)) {
									copiedData.splice(index, 1);
									index--;
								}
							}
							setSkuOptions(copiedData);
							setOpen(false);
						}}
					>
						<Button type="primary">确定</Button>
					</Popconfirm>
				) : (
					<Button
						type="primary"
						onClick={() => {
							const copiedData = cloneDeep(skuOptionRef.current?.getData() || []);
							setSkuOptions(copiedData);
							setOpen(false);
						}}
					>
						确定
					</Button>
				)
			}
		>
			<AttributeTable ref={skuOptionRef} label="sku选项" onChange={data => setOptions(data)} />
		</Modal>
	);
};

export default AddOptionModal;
